#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <postprocess.h>

float  ldGetNpuFreq()
{
    char ret[1024]={0};
    FILE *fp;
    float temp = 0.0f;

    fp= fopen("//sys/kernel/debug/rknpu/freq","rb");
    if(fp != nullptr)
    {
       int nread=fread(ret,1,1024,fp);
       if(nread > 0)
       {
               temp = atoi(ret)/1000000.0;
       }
       fclose(fp);
    }
    //printf("nread=%d,ret=%s\n",nread,ret);

    return temp;
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    qDebug() << "rk3588 npu freq " << ldGetNpuFreq() << "Mhz";

    m_pRknnCore0 = new RknnThread(NULL,0);
    if(m_pRknnCore0)
    {
        m_pRknnCore0->setStackSize(16 * 1024 * 1024);
        m_pRknnCore0->start();
    }

    m_pRknnCore1 = new RknnThread(NULL,1);
    if(m_pRknnCore1)
    {
        m_pRknnCore1->setStackSize(16 * 1024 * 1024);
        m_pRknnCore1->start();
    }

    m_pRknnCore2 = new RknnThread(NULL,2);
    if(m_pRknnCore2)
    {
        m_pRknnCore2->setStackSize(16 * 1024 * 1024);
        m_pRknnCore2->start();
    }


    m_pOneSecond = new QTimer(this);
    connect(m_pOneSecond, SIGNAL(timeout()), this, SLOT(OnHandleOneSecond()));
    m_pOneSecond->start(1000);

}

MainWindow::~MainWindow()
{
    delete ui;
    if(m_pRknnCore0)
    {
        m_pRknnCore0->Stop();
        m_pRknnCore0->wait();
        delete m_pRknnCore0;
    }
    if(m_pRknnCore1)
    {
        m_pRknnCore1->Stop();
        m_pRknnCore1->wait();
        delete m_pRknnCore1;
    }
    if(m_pRknnCore2)
    {
        m_pRknnCore2->Stop();
        m_pRknnCore2->wait();
        delete m_pRknnCore2;
    }
    deinitPostProcess();
}


void  ldGetNpuLoad(char* pNpuLoadStr)
{
    char ret[1024]={0};
    FILE *fp;
    float temp = 0.0f;

    fp= fopen("/sys/kernel/debug/rknpu/load","rb");
    if(fp != nullptr)
    {
       int nread=fread(ret,1,1024,fp);
       if(nread > 0)
       {
            strcpy(pNpuLoadStr,ret);
       }
       fclose(fp);
    }
    //printf("nread=%d,ret=%s\n",nread,ret);

    return ;
}

static int nSecond = 0;
void MainWindow::OnHandleOneSecond()
{
    char cBuff[512] = {0};
    nSecond ++;
    char cLoadStr[512] = {0};
    ldGetNpuLoad(cLoadStr);
    qDebug() << nSecond << "sec [0]" << m_pRknnCore0->GetFps() << "fps" <<
                               "[1]" << m_pRknnCore1->GetFps() << "fps" <<
                               "[2]" << m_pRknnCore2->GetFps() << "fps" << cLoadStr ;
    if(nSecond > 30)
    {
        qDebug() << "30 second app will exit" << endl;
        close();
    }
}
